<template>
	<view class="container">
		<view class="header">
			<view class="price-wrapper flex align-center">
				<text class="price"
					:style="{color:stockInfo.chajia>=0?getUpColor:getDownColor}">{{stockInfo.chajia>=0?stockInfo.Price+' ↑':stockInfo.Price&&stockInfo.Price+" ↓"}}</text>
				<text class="change-num">{{stockInfo.chajia>=0?"+"+stockInfo.chajia:stockInfo.chajia}}</text>
				<text class="change">{{stockInfo.chajia>=0?"+"+stockInfo.zhangfu:stockInfo.zhangfu}}%</text>
			</view>
			<view class="total-info flex">
				<text class="item">开:{{stockInfo.Open}}</text>
				<text class="item">收:{{stockInfo.BP1}}</text>
				<text class="item color-pink">高:<text :style="{color:stockInfo.chajia>=0?getUpColor:getDownColor}">{{stockInfo.High}}</text></text>
				<text class="item color-green">低:<text :style="{color:stockInfo.chajia>=0?getDownColor:getUpColor}">{{stockInfo.Low}}</text></text>
			</view>
		</view>
		<stock-tab :tabs="tabs" :currentActive="currentActive" @change="changeInterval"></stock-tab>
		<stock-echarts :newPrice="newPrice" :currentActive="currentActive" :chartData="chartData" @invokeGetKData="invokeGetKData">
		</stock-echarts>
		<view class="flex justify-center mt-30">
			<view class="sell-btn flex align-center justify-center" @tap="order(1)">
				<view class="flex align-center">
					<text class="label">卖出</text>
					<text class="value">{{stockInfo.BP1}}</text>
				</view>
			</view>
			<view class="buy-btn flex align-center justify-center" @tap="order(2)">
				<view class="flex align-center">
					<text class="value">{{stockInfo.SP1}}</text>
					<text class="label">买入</text>
				</view>
			</view>
		</view>
		<u-popup v-model="orderShow" mode="bottom" border-radius="14">
			<view class="order-popup-wrapper">
				<view class="header flex justify-center align-center">
					<view class="flex header-left align-center" @tap="toggleCloseShow">
						<u-icon name="arrow-down" size="24" color="#999"></u-icon>
						<text class="close-btn">止盈止损</text>
					</view>
					<text class="title">{{$Route.query.name}}</text>
					<view class="header-right-wrapper flex align-center">
						<u-icon name="close" size="30" color="#999" @tap="orderShow=false"></u-icon>
					</view>
				</view>
				<view class="flex justify-center">
					<view class="sell-popup-btn" :class="optionType==1?'sell-select':''" @tap="toggleOptionType(1)">
						卖出{{stockInfo.BP1}}</view>
					<view class="buy-popup-btn" :class="optionType==2?'buy-select':''" @tap="toggleOptionType(2)">
						买入{{stockInfo.SP1}}</view>
				</view>
				<view class="charge-form">
					<view class="flex justify-between align-center">
						<text class="charge-type-label">交易类型</text>
						<view class="flex">
							<view class="charge-type-item" :class="chargeType==1?'charge-type-item-select':''"
								@tap="toggleChargeType(1)">市价</view>
							<view class="charge-type-item" :class="chargeType==2?'charge-type-item-select':''"
								@tap="toggleChargeType(2)">限价</view>
						</view>
					</view>
					<view class="flex justify-end mt-30" v-if="chargeType==2">
						<u-number-box :positive-integer="false" :input-width="160" v-model="limitPrice" :step="0.01">
						</u-number-box>
					</view>
					<view class="limit-desc mt-30" v-if="chargeType==2" :class="isLimitValid?'color-gray':'up-color'">
						价格范围为{{optionType == 1?'>='+c_limit_min:'<='+c_limit_max}}</view>
					<view class="flex justify-between align-center mt-30">
						<text class="charge-type-label">手数</text>
						<u-number-box :positive-integer="false" v-model="num" :min="0"></u-number-box>
					</view>
					<template v-if="closeShow">
						<view class="close-title mt-30">止盈止损</view>
						<view class="flex justify-between align-center mt-30">
							<text class="close-label">止损</text>
							<view class="flex flex-column w-250 align-end">
								<u-number-box :positive-integer="false" :input-width="160" v-model="closeLosePrice"
									:step="parseFloat(stockInfo.number)"></u-number-box>
								<text class="desc-tip"
									:class="isCloseLoseValid?'color-gray':'up-color'">价格范围为{{c_loseClosePrice.unit}}{{c_loseClosePrice.value}}，<text
										v-if="closeLosePrice">预计盈亏{{c_loseCloseDelta}}</text></text>
							</view>
						</view>
						<view class="flex justify-between align-center mt-30">
							<text class="close-label">止盈</text>
							<view class="flex flex-column w-250 align-end">
								<u-number-box :positive-integer="false" :input-width="160" v-model="closeEarnPrice"
									:step="parseFloat(stockInfo.number)"></u-number-box>
								<text class="desc-tip"
									:class="isCloseEarnValid?'color-gray':'up-color'">价格范围为{{c_earnClosePrice.unit}}{{c_earnClosePrice.value}}，<text
										v-if="closeEarnPrice">预计盈亏{{c_earnCloseDelta}}</text></text>
							</view>
						</view>
					</template>

					<view class="flex justify-center mt-30">
						<text class="money-label">保证金</text>
						<text class="up-color f-24">{{parseFloat(stockInfo.pay_choose * num).toFixed(2)}}</text>
						<text class="money-label">元,可用资金</text>
						<text class="up-color f-24">{{money_keyong}}</text>
					</view>

					<view class="common-btn submit-btn" @tap="confirmOrder">确认开仓</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		createWebsocket,
		sendSocketMessage
	} from '@/websocket/index.js'
	import {
		mapGetters,
		mapState
	} from "vuex"

	export default {
		data() {
			return {
				newPrice:0,
				money_keyong: "",
				//倍数
				key: 8,
				//1表示做空 2表示做多
				optionType: 1,
				//交易类型 1表示市价 2表示限价
				chargeType: 1,
				//止盈止损
				closeShow: false,
				closeEarnPrice: 0,
				closeLosePrice: 0,
				limitPrice: 0,
				num: 1,
				orderShow: false,
				firstLoad: true,
				chartData: {},
				stockInfo: {},
				timer: null,
				requestTimer: null,
				tabs: [{
					name: "日K线",
					value: "d",
					timer: 60 * 24
				}, {
					name: "分时",
					value: 1,
					timer: 1
				}, {
					name: "M1",
					value: 1,
					timer: 1
				}, {
					name: "M5",
					value: 5,
					timer: 5
				}, {
					name: "M15",
					value: 15,
					timer: 15
				}, {
					name: "M30",
					value: 30,
					timer: 30
				}, {
					name: "H1",
					value: 60,
					timer: 62
				}],
				currentActive: 2,
				tailCount: 0
			};
		},
		computed: {
			...mapState("user", ["isMock"]),
			...mapGetters("user", ["getToken", "getUserInfo", "getUpColor", "getDownColor"]),
			isLimitValid() {
				if (this.optionType == 1) {
					return this.limitPrice >= this.c_limit_min
				} else {
					return this.limitPrice <= this.c_limit_max
				}
			},
			//限价最小值
			c_limit_min() {
				//做空
				if (this.optionType == 1) {
					return parseFloat((parseFloat(this.stockInfo.BP1) + this.key * parseFloat(this.stockInfo.number))
						.toFixed(this.tailCount))
				} else {
					return 0
				}
			},
			c_limit_max() {
				//做多
				if (this.optionType == 2) {
					return parseFloat((parseFloat(this.stockInfo.SP1) - this.key * parseFloat(this.stockInfo.number))
						.toFixed(this.tailCount))
				} else {
					return 100000000000
				}
			},
			//止损  价格范围
			c_loseClosePrice() {
				if (!this.stockInfo.SP1) {
					return "-"
				}
				let unit
				let value
				//卖出
				if (this.optionType == 1) {
					unit = ">="
					if (this.chargeType == 1) {
						value = parseFloat((parseFloat(this.stockInfo.SP1) + (parseFloat(this.stockInfo.number) * this
							.key)).toFixed(this.tailCount))
					} else {
						value = parseFloat((parseFloat(this.stockInfo.SP1) + (parseFloat(this.stockInfo.number) * this
							.key * 2)).toFixed(this.tailCount))
					}
				} else {
					unit = "<="
					if (this.chargeType == 1) {
						value = parseFloat((parseFloat(this.stockInfo.BP1) - (parseFloat(this.stockInfo.number) * this
							.key)).toFixed(this.tailCount))
					} else {
						value = parseFloat((parseFloat(this.stockInfo.BP1) - (parseFloat(this.stockInfo.number) * this
							.key * 2)).toFixed(this.tailCount))
					}
				}
				return {
					unit,
					value
				}
			},
			//止损 预计盈亏
			c_loseCloseDelta() {
				if (!this.stockInfo.SP1) {
					return "-"
				}
				let value

				let _money = parseFloat(this.stockInfo.money)
				let orderPrice
				if (this.chargeType == 1) {
					if (this.optionType == 1) {
						orderPrice = parseFloat(this.stockInfo.BP1)
					} else {
						orderPrice = parseFloat(this.stockInfo.SP1)
					}
				} else {
					orderPrice = this.limitPrice
				}
				//卖出
				if (this.optionType == 1) {
					value = (orderPrice - this.closeLosePrice) / parseFloat(this.stockInfo.number) * this.num * _money
				} else {
					value = ((orderPrice - this.closeLosePrice) / parseFloat(this.stockInfo.number) * this.num * _money) *
						(
							-1)
				}
				return value.toFixed(this.tailCount)
			},
			//止盈 价格范围
			c_earnClosePrice() {
				if (!this.stockInfo.SP1) {
					return "-"
				}
				let unit
				let value
				//卖出
				if (this.optionType == 1) {
					unit = "<="
					if (this.chargeType == 1) {
						value = parseFloat((parseFloat(this.stockInfo.SP1) - (parseFloat(this.stockInfo.number) * this
							.key)).toFixed(this.tailCount))
					} else {
						value = parseFloat((parseFloat(this.stockInfo.SP1)).toFixed(this.tailCount))
					}
				} else {
					unit = ">="
					if (this.chargeType == 1) {
						value = parseFloat((parseFloat(this.stockInfo.BP1) + (parseFloat(this.stockInfo.number) * this
							.key)).toFixed(this.tailCount))
					} else {
						value = parseFloat((parseFloat(this.stockInfo.BP1)).toFixed(this.tailCount))
					}
				}
				return {
					unit,
					value
				}
			},
			//止盈 预计盈亏
			c_earnCloseDelta() {
				if (!this.stockInfo.SP1) {
					return "-"
				}
				let value
				let _money = parseFloat(this.stockInfo.money)
				let orderPrice
				if (this.chargeType == 1) {
					if (this.optionType == 1) {
						orderPrice = parseFloat(this.stockInfo.BP1)
					} else {
						orderPrice = parseFloat(this.stockInfo.SP1)
					}
				} else {
					orderPrice = this.limitPrice
				}
				//卖出
				if (this.optionType == 1) {
					value = (orderPrice - this.closeEarnPrice) / parseFloat(this.stockInfo.number) * this.num * _money
				} else {
					value = ((orderPrice - this.closeEarnPrice) / parseFloat(this.stockInfo.number) * this.num * _money) *
						(
							-1)
				}
				return value.toFixed(this.tailCount)
			},
			isCloseLoseValid() {
				let _price = parseFloat(this.c_loseClosePrice.value)
				if (this.c_loseClosePrice.unit == ">=") {
					return this.closeLosePrice >= _price
				} else if (this.c_loseClosePrice.unit == "<=") {
					return this.closeLosePrice <= _price
				}
			},
			isCloseEarnValid() {
				let _price = parseFloat(this.c_earnClosePrice.value)
				if (this.c_earnClosePrice.unit == ">=") {
					return this.closeEarnPrice >= _price
				} else if (this.c_earnClosePrice.unit == "<=") {
					return this.closeEarnPrice <= _price
				}
			},
			c_min() {
				let _price = parseFloat(this.c_loseClosePrice.value)
				if (this.c_loseClosePrice.unit == ">=") {
					return _price
				} else if (this.c_loseClosePrice.unit == "<=") {
					return 0
				}
			},
			c_max() {
				let _price = parseFloat(this.c_loseClosePrice.value)
				if (this.c_loseClosePrice.unit == ">=") {
					return 10000000000
				} else if (this.c_loseClosePrice.unit == "<=") {
					return _price
				}
			},
			c_min_1() {
				let _price = parseFloat(this.c_earnClosePrice.value)
				if (this.c_earnClosePrice.unit == ">=") {
					return _price
				} else if (this.c_earnClosePrice.unit == "<=") {
					return 0
				}
			},
			c_max_1() {
				let _price = parseFloat(this.c_earnClosePrice.value)
				if (this.c_earnClosePrice.unit == ">=") {
					return 10000000000
				} else if (this.c_earnClosePrice.unit == "<=") {
					return _price
				}
			},
		},
		methods: {
			invokeGetKData() {
				//k线
				this.setRequestKdataTimer()
			},
			//确认下单
			async confirmOrder() {
				let newPrice
				if (this.chargeType == 1) {
					if (this.optionType == 1) {
						newPrice = parseFloat(this.stockInfo.BP1)
					} else {
						newPrice = parseFloat(this.stockInfo.SP1)
					}
				} else {
					newPrice = this.limitPrice
				}
				let params = {
					token: this.getToken,
					order_type: this.optionType == 1 ? 1 : 0,
					order_pid: this.$Route.query.id,
					order_price: this.stockInfo.pay_choose,
					newprice: newPrice,
					onumber: this.num,
					surplus: this.closeEarnPrice,
					loss: this.closeLosePrice,
				}
				//市价
				if (this.chargeType == 1) {
					try {
						let res = await this.$u.api.addOrderApi(params)
						this.$Router.push({
							path: "/pages/orderSuccess/orderSuccess",
							query: {
								title: "下单开仓成功"
							}
						})
					} catch (e) {
						console.log("e", e)
						//TODO handle the exception
					}
				}
				//限价 挂单
				else {
					try {
						let res = await this.$u.api.penddingOrderApi(params)
						this.$Router.push({
							path: "/pages/orderSuccess/orderSuccess",
							query: {
								title: "挂单成功"
							}
						})
					} catch (e) {
						//TODO handle the exception
					}

				}
			},
			toggleChargeType(type) {
				this.chargeType = type
				if (type == 2) {
					if (this.optionType == 1) {
						this.limitPrice = parseFloat((parseFloat(this.stockInfo.BP1) + this.key * parseFloat(this.stockInfo
							.number)).toFixed(this.tailCount))
					} else {
						this.limitPrice = parseFloat((parseFloat(this.stockInfo.SP1) - this.key * parseFloat(this.stockInfo
							.number)).toFixed(this.tailCount))
					}
				}
				//止盈止损展开才设置
				if (this.closeShow) {
					this.closeEarnPrice = this.c_earnClosePrice.value
					this.closeLosePrice = this.c_loseClosePrice.value
				}

			},
			toggleOptionType(type) {
				this.optionType = type
				//止盈止损展开才设置
				if (this.closeShow) {
					this.closeEarnPrice = this.c_earnClosePrice.value
					this.closeLosePrice = this.c_loseClosePrice.value
				}

				if (this.chargeType == 2) {
					if (this.optionType == 1) {
						this.limitPrice = parseFloat((parseFloat(this.stockInfo.BP1) + this.key * parseFloat(this.stockInfo
							.number)).toFixed(this.tailCount))
					} else {
						this.limitPrice = parseFloat((parseFloat(this.stockInfo.SP1) - this.key * parseFloat(this.stockInfo
							.number)).toFixed(this.tailCount))
					}
				}
			},

			loseChange({
				value
			}) {
				let _price = parseFloat(this.c_loseClosePrice.value)
				if (this.c_loseClosePrice.unit == ">=") {
					if (value < _price) {
						setTimeout(() => {
							this.closeLosePrice = _price
						}, 200)
					}
				} else if (this.c_loseClosePrice.unit == "<=") {
					if (value > _price) {
						setTimeout(() => {
							this.closeLosePrice = _price
						}, 200)
					}
				}
			},
			earnChange({
				value
			}) {
				let _price = parseFloat(this.c_earnClosePrice.value)
				console.log("value is", _price)
				if (this.c_earnClosePrice.unit == ">=") {
					if (value < _price) {
						setTimeout(() => {
							this.closeEarnPrice = _price
						}, 200)
					}
				} else if (this.c_earnClosePrice.unit == "<=") {
					if (value > _price) {
						console.log("trigger----", value)
						setTimeout(() => {
							this.closeEarnPrice = _price
						}, 200)
					}
				}
			},
			toggleCloseShow() {
				if (this.closeShow) {
					this.closeEarnPrice = 0
					this.closeLosePrice = 0
				} else {
					this.closeEarnPrice = this.c_earnClosePrice.value
					this.closeLosePrice = this.c_loseClosePrice.value
				}
				this.closeShow = !this.closeShow
			},
			order(type) {
				this.optionType = type
				this.orderShow = true
			},
			setRequestKdataTimer() {
				this.clearRequestTimer()
				this.requestKdata()
				this.requestTimer = setInterval(() => {
					this.requestKdata()
				}, 1000 * 60 * (this.tabs[this.currentActive].timer))
			},
			clearRequestTimer() {
				if (this.requestTimer) {
					clearInterval(this.requestTimer)
					this.requestTimer = null
				}
			},
			async requestKdata() {
				try {
					this.chartData = await this.$u.api.getKDataApi({
						pid: this.$Route.query.id,
						interval: this.tabs[this.currentActive].value,
						num: 1000
					})

				} catch (e) {
					//TODO handle the exception
				}

			},
			changeInterval(index) {
				if (index == this.currentActive) {
					return
				}
				this.currentActive = index
				this.setRequestKdataTimer()
			},
			websocketOpenCallback() {
				console.log("this.$Route.query.id", this.$Route.query.id, "this.$Route.query.name", this.$Route.query.name)
				sendSocketMessage(JSON.stringify({
					action: "fordata",
					pid: this.$Route.query.id,
					token: this.getToken
				}))
				this.timer = setInterval(() => {
					sendSocketMessage(JSON.stringify({
						action: "fordata",
						pid: this.$Route.query.id,
						token: this.getToken
					}))
				}, 1000)
			},
			websocketMessageCallback({
				data
			}) {
				if (this.firstLoad) {
					uni.hideLoading();
					this.firstLoad = false
				}
				if (data.action == "fordata") {
					this.stockInfo = data.res.data.pro
					this.newPrice=parseFloat(this.stockInfo.Price)
					this.money_keyong = data.res.data.jiaoy_info.money_keyong
					this.tailCount = this.stockInfo.number.split(".")[1] ? this.stockInfo.number.split(".")[1].length : 1
				}
			}
		},
		onShow() {
			//显示加载
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			setTimeout(() => {
				uni.hideLoading();
			}, 3000)
			uni.setNavigationBarTitle({
				title: this.$Route.query.name
			})
			//websocket
			createWebsocket()
			this.websocketOpenCallback()
			uni.$on("websocketMessage", this.websocketMessageCallback)
			
			if(!this.requestTimer&&!this.firstLoad){
				this.setRequestKdataTimer()
			}

		},
		onHide() {
			uni.$off("websocketMessage", this.websocketMessageCallback)
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.clearRequestTimer()
		},
		onUnload() {
			uni.$off("websocketMessage", this.websocketMessageCallback)
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.clearRequestTimer()
		}
	}
</script>

<style lang="scss">
	.container {
		background-color: #fff;

		.color-gray {
			color: #999;
		}

		.header {
			padding: 10rpx 30rpx;

			.price-wrapper {
				.price {
					font-size: 34rpx;
					font-weight: bold;
				}

				.change-num {
					margin: 0 10rpx;
					font-size: 24rpx;
				}

				.change {
					font-size: 24rpx;
				}
			}

			.total-info {
				margin-top: 10rpx;

				.item {
					font-size: 24rpx;
					flex: 1;
					text-align: center;
				}
			}
		}

		.sell-btn {
			margin-right: 50rpx;
			width: 300rpx;
			height: 70rpx;
			border-radius: 10rpx;
			background-color: $color-green;
		}

		.value {
			color: #fff;
			font-size: 32rpx;
			line-height: 32rpx;
		}

		.label {
			margin: 0 10rpx;
			color: #fff;
			font-size: 24rpx;
			line-height: 24rpx;
		}

		.buy-btn {
			width: 300rpx;
			height: 70rpx;
			border-radius: 10rpx;
			background-color: $color-pink;
		}

		.order-popup-wrapper {
			.header {
				position: relative;
				padding: 30rpx;
				height: 40rpx;
				box-sizing: content-box;

				.header-left {
					position: absolute;
					left: 30rpx;
					top: 30rpx;
					height: 40rpx;
				}

				.header-right-wrapper {
					position: absolute;
					right: 30rpx;
					top: 30rpx;
					height: 40rpx;
				}

				.close-btn {
					margin-left: 10rpx;
					font-size: 24rpx;
					color: #333;
				}

				.title {
					font-size: 30rpx;
					color: #333;
				}
			}

			.sell-popup-btn {
				width: 250rpx;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				font-size: 24rpx;
				color: $color-green;
				border: 1rpx solid #ddd;
				border-radius: 10rpx 0 0 10rpx;
			}

			.sell-select {
				border: 1rpx solid $color-green;
			}

			.buy-popup-btn {
				width: 250rpx;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				font-size: 24rpx;
				color: $color-pink;
				border: 1rpx solid #ddd;
				border-radius: 0 10rpx 10rpx 0;
			}

			.buy-select {
				border: 1rpx solid $color-pink;
			}

			.charge-form {
				padding: 30rpx;

				.limit-desc {
					font-size: 24rpx;
					text-align: right;
				}

				.charge-type-label {
					font-size: 24rpx;
					color: #333;
				}

				.charge-type-item {
					margin-right: 20rpx;
					border: 1rpx dashed #ddd;
					color: $color-blue;
					font-size: 20rpx;
					border-radius: 10rpx;
					padding: 10rpx 20rpx;

					&:last-child {
						margin-right: 0;
					}
				}

				.charge-type-item-select {
					border: 1rpx solid $color-blue;
					background-color: $color-gray;
				}

				.money-label {
					font-size: 24rpx;
					color: #333;
				}

				.f-24 {
					font-size: 24rpx;
				}

				.submit-btn {
					margin-top: 50rpx;
					height: 70rpx;
					border-radius: 20rpx;
					font-size: 30rpx;
					line-height: 70rpx;
				}

				.close-label {
					font-size: 24rpx;
					color: #333;
				}

				.w-250 {
					width: 500rpx;
				}

				.desc-tip {
					margin-top: 10rpx;
					font-size: 20rpx;
				}
			}
		}

	}
</style>
